#!/bin/sh /etc/rc.common

START=90
SERVICE_USE_PID=1
SERVICE_WRITE_PID=1
SERVICE_DAEMONIZE=1
EXTRA_COMMANDS="firewall restart"

APP='adbyby'

check_prerouting() {
	if iptables -t nat --list zone_lan_prerouting &>/dev/null; then
		PREROUTING='zone_lan_prerouting'
	else
		PREROUTING='PREROUTING'
	fi
}

iptables_flush() {
	iptables-restore <<-EOF || {
		$(echo -e "$(iptables-save -t nat)" | sed '/ADBYBY/d')
	EOF
		[ -z "$PREROUTING" ] && check_prerouting
		iptables -t nat -F ADBYBY
		iptables -t nat -D $PREROUTING -p tcp -j ADBYBY
		iptables -t nat -X ADBYBY
	}
	return $?
}

iptables_restore() {
	[ -z "$PREROUTING" ] && check_prerouting
	iptables-restore -n <<-EOF
		*nat
		:ADBYBY - [0:0]
		-A ADBYBY -d 0.0.0.0/8 -j RETURN
		-A ADBYBY -d 10.0.0.0/8 -j RETURN
		-A ADBYBY -d 100.64.0.0/10 -j RETURN
		-A ADBYBY -d 127.0.0.0/8 -j RETURN
		-A ADBYBY -d 169.254.0.0/16 -j RETURN
		-A ADBYBY -d 172.16.0.0/12 -j RETURN
		-A ADBYBY -d 192.0.0.0/24 -j RETURN
		-A ADBYBY -d 192.0.2.0/24 -j RETURN
		-A ADBYBY -d 192.88.99.0/24 -j RETURN
		-A ADBYBY -d 192.168.0.0/16 -j RETURN
		-A ADBYBY -d 198.18.0.0/15 -j RETURN
		-A ADBYBY -d 198.51.100.0/24 -j RETURN
		-A ADBYBY -d 203.0.113.0/24 -j RETURN
		-A ADBYBY -d 224.0.0.0/4 -j RETURN
		-A ADBYBY -d 240.0.0.0/4 -j RETURN
		-A ADBYBY -d 255.255.255.255 -j RETURN
		-A ADBYBY -p tcp --dport 80 -j REDIRECT --to-ports 8118
		-A $PREROUTING -p tcp -j ADBYBY
		COMMIT
	EOF
}

service_enabled_check() {
	config_load "$APP"
	config_get enabled config enabled
	[ "$enabled" = '1' ] || {
		return 1
	}
	return 0
}

service_options() {
	config_get path config path '/usr/bin/adbyby'
	[ -f "$path" ] || {
		echo "File $pat does not exist."
		return 1
	}
	return 0
}

service_check() {
	FIND_DATA=$(ps|grep "$1"|grep -v "grep $1")
	[ -z "$FIND_DATA" ] && return 1
	return 0
}

service_process() {
	service_check "$1" && echo "Start $1 ... Already running. Please try \"stop\" or \"restart\"" && return 1
	service_start $1 $2
	service_check "$1" && echo "Start $1 ... OK" && return 0
	echo "Start $1 ... Fail" && return 1
}

service_run() {
	service_options && service_process "$path" && return 0
	return 1
}

start() {
	service_enabled_check || exit 0
	service_run && {
		iptables_flush
		iptables_restore
	}
}

stop() {
	iptables_flush
	config_load "$APP"
	service_options && service_stop $path
}

restart() {
	service_enabled_check || {
		iptables_flush
		service_options && service_stop $path
		exit 0
	}
	service_options && service_stop $path
	service_run && {
		iptables_flush
		iptables_restore
	}
}

firewall() {
	iptables_restore
	exit 0
}
